const qs = require('querystring')
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer()
server.on('request', (req, res) => { 
  if (req.url === '/api/province') {
    fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
      if (err) return console.log(err)

      const arr = JSON.parse(data.tongString())
      const plist = arr.map(item => item.provinceName)
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(plist))
    })
  } else if (req.url.startsWith('/api/city')) {
    const queryStr = req.url.split('?')[1]
    const queryObj = qs.parse(queryStr)
    const pname = queryObj.pname
    fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
      if (err) return console.log(err)
      const arr = JSON.parse(data.toString())
      const pObj = arr.find(obj => obj.provinceName === pname)
      const clist = pObj.cities.map(item => item.cityName)
    
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(clist))
    })
  } else if (req.url.startsWith('/api/area')) {
    const areaStr = req.url.split('?')[1]
    const areaObj = qs.parse(areaStr)
    const pname = areaObj.pname
    const cname = areaObj.cname
    fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
      if (err) return console.log(err)
      const arr = JSON.parse(data.toString())
      const pObj = arr.find(obj => obj.provinceName === pname)
      const cObj = pObj.cities.find(obj => obj.cityName === cname)
      const alist = cObj.counties.map(item => item.countyName)
    
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(alist))
    })
  }else {
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('访问的资源不存在')
  }
})
server.listen(3000, () => console.log('服务器启动'))